package com.ruoyi.framework.security.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;

/**
 * token过滤器 验证token有效性
 * 
 * @author ruoyi
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    /**
     * TokenService类是token验证处理*/
    @Autowired
    private TokenService tokenService;

    /**
     * 从http请求中提取令牌
     * 验证令牌的有效性和过期时间
     * 刷新令牌有效期（可选）
     * 解析令牌获取用户信息
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        /*调用getLoginUser方法：获取用户身份信息*/
        LoginUser loginUser = tokenService.getLoginUser(request);
        //根据getAuthentication方法获取Authentication
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
        {
            //验证令牌有效期，自动刷新缓存
            tokenService.verifyToken(loginUser);
            //用户认证成功后，使用实现类UsernamePasswordAuthenticationToken将用户对象，权限存储在authentication中，
            //此处调用的getAuthorities方法返回值为null，但是权限信息是此处在logingUser中的permissions权限列表中
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            //将认证信息存入SecurityContext，后期过滤器或资源都是从Context中取用户信息
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        //继续执行过滤器链
        chain.doFilter(request, response);
    }
}
